<template>
  <div class="flex flex-wrap gap-4 items-center area">
    <el-select
        v-model="selectedArea.province"
        class="area-select"
        placeholder="请选择省份"
        @change="onProvinceChange"
        filterable
    >
      <el-option
          v-for="(value, key) in provinceList"
          :key="key"
          :label="value"
          :value="key"
      />
    </el-select>
    <el-select
        v-model="selectedArea.city"
        class="area-select"
        placeholder="请选择市"
        @change="onCityChange"
        filterable
    >
      <el-option
          v-for="(value, key) in cityList"
          :key="key"
          :label="value"
          :value="key"
      />
    </el-select>
  </div>
</template>

<script setup>
import {ref, watch} from 'vue'
import {areaList} from "@vant/area-data";
const props = defineProps({
  modelValue : {
    type: Object,
    default: () => ({ province: '', city: '' })
  }
})
const emit = defineEmits(['update:modelValue'])
const selectedArea = ref({ ...props.modelValue })

// const province = ref('')
// const city = ref('')

const provinceList = ref(areaList.province_list)
const cityList = ref(areaList.city_list)

const onProvinceChange = (value) => {
  const code = value.slice(0, 2)
  cityList.value = Object.keys(areaList.city_list).filter(key => key.startsWith(code)).reduce((obj, key)=>{
    obj[key] = areaList.city_list[key];
    return obj
  },{})
  // city.value=''
  selectedArea.value.province = provinceList.value[value]
  selectedArea.value.city=''
}

const onCityChange = (value) => {
  // if(!province.value){
  //   const provinceCode = value.slice(0, 2).concat('0000')
  //   province.value = provinceList.value[provinceCode]
  // }
  const provinceCode = value.slice(0, 2).concat('0000')
  selectedArea.value.province = provinceList.value[provinceCode]
  selectedArea.value.city = cityList.value[value]

  // emit('update:modelValue', cityList.value[value]);
  emit('update:modelValue', selectedArea);
}

watch(selectedArea, (newVal) => {
  emit('update:modelValue', newVal);
}, { deep: true });

</script>

<style scoped lang="less">
.area {
  display: flex;
  flex-direction: row;
}

.area-select {
  min-width: 120px;
}

.area-select:last-child {
  margin-left: 5px;
}
</style>